from django.shortcuts import render

# Create your views here.
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from myproject.models import Myproject
from module.models import Module
from module.serializer import ModuleSerializers
from utils.errormsg import erromsg
from utils.pagination import MyPagePagination
from utils.status import CODE_1, CODE_0


class ModuleViews(ModelViewSet):
    queryset = Module.objects.all()
    serializer_class = ModuleSerializers
    permission_classes = [IsAuthenticated]
    pagination_class = MyPagePagination

    def new_module(self, request: Request):
        user = request.user
        data = request.data
        projectid = data.get("project_id")

        serializer = self.serializer_class(data=data, context={"user": user})
        if not serializer.is_valid():
            return Response({**CODE_1, "msg": erromsg(serializer)})
        project = Myproject.objects.filter(id=projectid, user=user)
        if not project:
            return Response({**CODE_1, "msg": "项目不存在"})

        serializer.save()

        return Response({**CODE_0, "data": serializer.data})

    def module_list(self, request: Request):
        user = request.user
        param = request.query_params
        queryset = self.queryset.filter(project__user_id=user.id)

        modulename = param.get("modulename")
        projectname = param.get("projecetname")
        if projectname:
            queryset = queryset.filter(projectname__contains=projectname)
        if modulename:
            queryset = queryset.filter(modulename__contains=modulename)

        queryset = self.paginate_queryset(queryset)
        serializer = self.serializer_class(queryset, many=True)
        data = self.get_paginated_response(serializer.data)
        return Response({**CODE_0, **data})

    def edit_module(self, request: Request, pk):
        user = request.user
        data = request.data

        queryset = self.queryset.filter(project__user_id=user.id, id=pk)
        if not queryset:
            return Response({**CODE_1, "msg": "不存在"})
        instance = queryset.get(id=pk)
        serializer = self.serializer_class(instance, data=data)
        if not serializer.is_valid():
            return Response({**CODE_1, "msg": erromsg(serializer)})

        serializer.save()
        data = serializer.data
        return Response({**CODE_0, "data": data})

    def del_module(self, request: Request, pk):
        user = request.user
        queryset = self.queryset.filter(project__user_id=user.id, id=pk)
        if not queryset:
            return Response({**CODE_1, "msg": "不存在"})
        queryset.delete()
        return Response({**CODE_0})
